<template>
  <!-- 退费管理 设置 -->
  <div class="pageWrap">
    <!-- type="card" -->
    <el-tabs v-model="activeGroup" @tab-click="groupChange">
      <el-tab-pane v-for="(v,i) in groupArr" :key="i" :label="v.name" :name="'g'+i"></el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item :model="formItem" label="状态">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="formItem.refundState"
          active-text="开启退费"
          inactive-text="关闭退费"
        ></el-switch>
      </el-form-item>
      <el-form-item label="退款规则">
        <el-button @click="addRefund">添加</el-button>
        <el-table :data="formItem.list" style="width: 100%">
          <el-table-column label="时间" width="420">
            <template slot-scope="{row,$index}">
              <el-date-picker
                v-model="row.date"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy/MM/dd HH:mm:ss"
                format="yyyy/MM/dd HH:mm:ss"
                @change="dateChange(row,$index)"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="策略" width="180">
            <template slot-scope="{row}">
              <el-select v-model="row.unit" placeholder="请选择">
                <el-option label="百分比" :value="2"></el-option>
                <el-option label="金额" :value="1"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="值">
            <template slot-scope="{row}">
              <el-input v-if="row.unit=='2'" placeholder="请输入内容" v-model="row.price">
                <template slot="append">%</template>
              </el-input>
              <el-input v-else placeholder="请输入内容" v-model="row.price">
                <template slot="append">元/人</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="{$index}">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="formItem.list.splice($index,1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="savePut">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formItem: {
        refundState: 0,
        list: [
          // unit 1:指定退的金额，2：几折（百分比）
          // { startDate: "", endDate: "", date: "", price: "", unit: 2 },
        ],
      },
      activeGroup: "g0",
      groupArr: [],
    };
  },
  methods: {
    dateChange(row, i) {
      if (row.date) {
        let hasCT = this.formItem.list.find((v, s) => {
          if (
            s != i &&
            isDateIntersection(row.date[0], row.date[1], v.date[0], v.date[1])
          ) {
            return v;
          }
        });
        if (hasCT) {
          row.date = "";
          this.$message.error("时间段冲突，请重新设置");
        }
      }
      this.$forceUpdate();
    },
    groupChange() {
      let ii = this.activeGroup.replace(/g/g, "");
      let oo = {
        groupId: this.groupArr[ii].id,
      };
      this.$axios
        .get("/sbr/applySet/getMatchRefundRule", { params: oo })
        .then((res) => {
          let rr = res.data.data;
          //   console.log(rr);
          if (rr) {
            rr.list.forEach((v) => {
              v.date = [v.startDate, v.endDate];
            });
            this.formItem = rr;
          } 
          // else {
          //   this.formItem = JSON.parse(
          //     JSON.stringify({
          //       refundState: 0,
          //       list: [
          //         // unit 1:指定退的金额，2：几折（百分比）
          //         { startDate: "", endDate: "", date: "", price: "", unit: 2 },
          //       ],
          //     })
          //   );
          // }
        });
    },
    // 获取赛项
    getGroupArr() {
      this.$axios
        .get("/sbr/match/getMatchInfos/" + sessionStorage.getItem("MandA"))
        .then((res) => {
          let rr = res.data.data;
          this.groupArr = rr.matchInfoLists;
          this.groupChange();
        });
    },
    // 添加退款规则
    addRefund() {
      this.formItem.list.push(
        JSON.parse(
          JSON.stringify({
            startDate: "",
            endDate: "",
            date: "",
            price: "",
            unit: 2,
          })
        )
      );
    },
    savePut() {
      let ii = this.activeGroup.replace(/g/g, "");
      this.formItem.matchId = Number(
        this.$Base64.decode(sessionStorage.getItem("MandA"))
      );
      this.formItem.groupId = this.groupArr[ii].id;
      let empty = this.formItem.list.find((v) => {
        // console.log(!v.date, !v.price);
        if (!v.date || !v.price) return v;
      });
      // console.log(empty);
      // if (empty) {
      //   this.$message.error("请设置退款时间与相应值");
      //   return false;
      // }
      this.formItem.list.forEach((v) => {
        v.startDate = v.date[0];
        v.endDate = v.date[1];
        v.price = Number(v.price);
      });
      this.$axios
        .post("/sbr/applySet/putMatchRefundRule", this.formItem)
        .then((res) => {
          this.groupChange();
        });
    },
  },
  created() {
    this.getGroupArr();
  },
};
//判断两个时间是否有交集
function isDateIntersection(start1, end1, start2, end2) {
  var startdate1 = new Date(start1.replace("-", "/"));
  var enddate1 = new Date(end1.replace("-", "/"));
  var startdate2 = new Date(start2.replace("-", "/"));
  var enddate2 = new Date(end2.replace("-", "/"));

  if (startdate1 >= startdate2 && startdate1 <= enddate2) {
    return true;
  }

  if (enddate1 >= startdate2 && enddate1 <= enddate2) {
    return true;
  }

  if (startdate1 <= startdate2 && enddate1 >= enddate2) {
    return true;
  }
  return false;
}
</script>
<style scoped>
.pageWrap {
  margin-bottom: 16px;
}
</style>